<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      v-show="showSearch"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="公司名称" prop="customerName">
        <el-input
          v-model="queryParams.customerName"
          placeholder="请输入公司名称"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目名称" prop="caseName">
        <el-input
          v-model="queryParams.caseName"
          placeholder="请输入项目名称"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设计师" prop="stylist">
        <el-input
          v-model="queryParams.stylist"
          placeholder="请输入设计师"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="创建时间" style="width: 308px">
        <el-date-picker
          v-model="dateRange"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          v-hasPermi="['system:case:add']"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:case:update']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:business:delete']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:role:export']"
          >導出</el-button
        >
      </el-col>
      <el-col :span="1.5">
           <el-button 
            v-if="close"
              type="warning" 
              plain 
              icon="Close"
              @click="handleClose"
           >关闭</el-button>
        </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格数据 -->
    <el-table
      v-loading="loading"
      :border =true 
      :data="caseList"
      @selection-change="handleSelectionChange"
    >
    <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="客戶" prop="customerName" width="120" />  
      <el-table-column label="客戶簡稱" prop="abbreviation" width="120" />
      <el-table-column label="聯繫人" prop="name" width="100" />
      <el-table-column label="負責業務" prop="nickName" width="100" />
      <el-table-column label="項目名稱" :show-overflow-tooltip="true" prop="caseName" width="90" />
      <el-table-column label="開案日期" prop="offerDate" width="90" :show-overflow-tooltip="true" />
      <el-table-column label="預計出貨日" prop="caseDate" width="90" />
      <el-table-column label="案值NTD" prop="progressStatement"  :show-overflow-tooltip="true"/>
      <el-table-column label="進度狀態" prop="schedule"  :show-overflow-tooltip="true"/>
      <el-table-column label="案件紀錄" prop="progressStatement"  :show-overflow-tooltip="true"/>
      
      <!-- <el-table-column label="创建时间" :show-overflow-tooltip="true"  prop="createTime" width="120">
      </el-table-column>
      <el-table-column label="创建人"  prop="createBy"></el-table-column> -->
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <!-- <el-tooltip
            content="拜访"
            placement="top"
           
          >
            <el-button
              link
              type="primary"
              icon="EditPen"
              @click="handleAuthbusiness(scope.row)"    
              v-hasPermi="['system:case:add']"
            ></el-button>
          </el-tooltip> -->
          <el-tooltip
            content="修改"
            placement="top"
           
          >
            <el-button
              link
              type="primary"
              icon="Edit"
              
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:case:update']"
            ></el-button>
          </el-tooltip>
          <el-tooltip
            content="删除"
            placement="top"
          >
            <el-button
              link
              type="primary"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:case:delete']"
            ></el-button>
          </el-tooltip>
          <!-- <el-tooltip content="数据权限" placement="top" v-if="scope.row.roleId !== 1">
                 <el-button link type="primary" icon="CircleCheck" @click="handleDataScope(scope.row)" v-hasPermi="['system:role:edit']"></el-button>
               </el-tooltip>
               <el-tooltip content="分配用户" placement="top" v-if="scope.row.roleId !== 1">
                 <el-button link type="primary" icon="User" @click="handleAuthUser(scope.row)" v-hasPermi="['system:role:edit']"></el-button>
               </el-tooltip> -->
        </template>
      </el-table-column>
    </el-table>
    <pagination
         v-show="total > 0"
         :total="total"
         v-model:page="queryParams.pageNum"
         v-model:limit="queryParams.pageSize"
         @pagination="getList"
      />
    

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" v-model="open" width="700px"  append-to-body>
      <el-form ref="addclientele" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="客户名称:" prop="customerName">
          <el-autocomplete

        v-model="form.customerName"
        :fetch-suggestions="querySearch"
        clearable
        class="inline-input"
        placeholder="请选择公司"
        @select="handleSelectID"
      />
        </el-form-item>

        <el-form-item label="项目名称:" prop="caseName">
          <el-input v-model="form.caseName" placeholder="请输入项目名称" />
        </el-form-item>
      
        <el-form-item label="设计师:" prop="stylist">
          <el-input v-model="form.stylist" placeholder="请输入设计师名称" />
        </el-form-item>

           
        <el-form-item label="案值:" prop="caseValue">
          <el-input v-model="form.caseValue" placeholder="请输入案值" />
        </el-form-item>
        

                 
        <el-form-item label="项目说明:"  prop="projectDescription">
          <el-input :rows="2" type="textarea" v-model="form.projectDescription" placeholder="请输入项目说明" />
        </el-form-item>
        
        <el-form-item label="灯具使用:" prop="useLamps">
          <el-input :rows="2" type="textarea" v-model="form.useLamps" placeholder="请输入灯具使用" />
        </el-form-item>
        
        <el-form-item label="进度:" prop="schedule">
          <el-input v-model="form.schedule" placeholder="请输入进度" />
        </el-form-item>


        <el-form-item label="进度说明:" prop="progressStatement">
          <el-input :rows="2" type="textarea" v-model="form.progressStatement" placeholder="请输入进度说明" />
        </el-form-item>

        
        <el-form-item label="最后维护日:" prop="lastTime">
          <el-date-picker
        v-model="form.lastTime"
        type="Date"
        placeholder="选择日期"
        :size="size"
        value-format="YYYY-MM-DD"
      />
        </el-form-item> 
    
      </el-form>

    

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

 
  </div>
</template>
 
 <script setup name="case">
import {
  listcase,
  addcase,
  getcase,
  delcase,
  updatecase,
  getcasebybusinessId,
} from "@/api/business/case.js";

import {
  listbusinesscustomerName,
} from "@/api/business/add.js";



import { ref} from "vue";



const router = useRouter();
const { proxy } = getCurrentInstance();


// 解构数据



// 初始化格式化的选项数据
const formattedOptions = ref([]);
const caseList=ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const loadAll=ref([])
const route = useRoute();
const close = ref(false);




const data = reactive({
  form: {
    businessId:""
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    businessId: route.params.Id,
  },
  rules: {
    customerName: [
      { required: true, message: "客户名称不能为空", trigger: "blur" },
    ],

    caseName: [
      { required: true, message: "项目名称不能为空", trigger: "blur" },
    ],

  },
});

const { queryParams, form, rules } = toRefs(data);

// 返回按钮
function handleClose() {
 const obj = { path: "/business/business/add" };
 proxy.$tab.closeOpenPage(obj);
}

/** 查询列表 */
function getList() {
  loading.value = true;

if(queryParams.value.businessId!=""&& queryParams.value.businessId!=undefined){
 
  getcasebybusinessId(queryParams.value.businessId,dateRange.value).then(response => {
    close.value = true;
    caseList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  }).catch(error => {
    loading.value = false;
  });


} else{ 
  listcase(queryParams.value,dateRange.value).then(response => {
    caseList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  }).catch(error => {
    loading.value = false;
  });
}
};


/** 查询公司列表  应该是全查现在是分页*/
function getListbusiness() {
  loading.value = true;
  listbusinesscustomerName(queryParams.value.businessId,dateRange.value).then(response => {
    const customerNames = response.rows.map(item => ({
      value: item.customerName,
      businessId: item.id,
      link: item.customerName // 可以根据实际情况添加链接
    }));
    loadAll.value = customerNames;
    loading.value = false;
  }).catch(error => {
    console.error('Failed to fetch company list:', error);
    loading.value = false;

  })
};




//远程选择客户名称
const querySearch = (queryString, cb) => {
  const results = queryString
    ? loadAll.value.filter(createFilter(queryString))
    : loadAll.value
  cb(results)
}
//远程选择客户名称
const createFilter = (queryString) => {
  return (loadAll) => {
    return (
      loadAll.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
    )
  }
}

// 选择事件处理
const handleSelectID = (item) => {

  // 可以在这里做进一步的操作，例如设置其他属性或触发其他事件
  data.form.businessId = item.businessId; // 将选择的 ID 存储到 state2 中
};



/** 查看联系人 */
function handleAuthbusiness(row) {

  router.push("/business/business-journal/index/" + row.id); 
}









/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}
/** 删除按钮操作 */
function handleDelete(row) {

  const id = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除为"' + id + '"的数据项?')
    .then(function () {
      return delcase(id);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}
/** 導出按钮操作 */
function handleExport() {
  proxy.download(
    "case/export",
    {
      ...queryParams.value,
    },
    `case_${new Date().getTime()}.xlsx`
  );
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
/** 角色状态修改 */
function handleStatusChange(row) {
  let text = row.status === "0" ? "启用" : "停用";
  proxy.$modal
    .confirm('确认要"' + text + '""' + row.roleName + '"角色吗?')
    .then(function () {
      return changeRoleStatus(row.roleId, row.status);
    })
    .then(() => {
      proxy.$modal.msgSuccess(text + "成功");
    })
    .catch(function () {
      row.status = row.status === "0" ? "1" : "0";
    });
}
/** 更多操作 */
function handleCommand(command, row) {
  switch (command) {
    case "handleDataScope":
      handleDataScope(row);
      break;
    case "handleAuthUser":
      handleAuthUser(row);
      break;
    default:
      break;
  }
}

function reset() {
  form.value = {
  
  };
  proxy.resetForm("addclientele");
}
/** 添加角色 */
function handleAdd() {
  reset();

  open.value = true;
  title.value = "添加案件";
  getListbusiness();
}
/** 修改角色 */
function handleUpdate(row) {
  reset();

  const id = row.id || ids.value;
  getcase(id).then(response => {
    form.value = response.data;
    open.value = true;
         // 将 row 中的 countiesCities 通过 '-' 分割并复制到 countiesCities 数组中
    title.value = "修改角色";
  })
 
}


/** 提交按钮 */
function submitForm() {

  proxy.$refs["addclientele"].validate((valid) => {
    if (valid) {

// 合并数据
const mergedData = { ...form.value};
      if (form.value.id != undefined) {     
        updatecase(mergedData).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addcase(mergedData).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();


}




getList(); 
</script>

<style scoped>
.linkman-input-group {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.linkman-input-group .el-input {
  flex: 1;
  margin-right: 10px;
}
</style>